package com.epam.action;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.epam.dao.h2.H2CourseDao;
import com.epam.dao.h2.H2TrainingDao;
import com.epam.entity.Course;
import com.epam.entity.Student;
import com.epam.entity.Training;

public class AddCourseAction implements Action {
	private static Logger LOGGER = LoggerFactory.getLogger(AddCourseAction.class);
	private static H2CourseDao h2CourseDao = new H2CourseDao();
	private static H2TrainingDao h2TrainingDao = new H2TrainingDao();
	
	@Override
	public String perform(HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("courseid");
		Pattern p = Pattern.compile("[0-9]+");

		if (id == "") {
			request.getSession().setAttribute("errorMessage",
					" Id must not be empty");
			request.getSession().setAttribute("initialpage",
					"/studentscabinet.jsp");
			return "/errormessage.jsp";
		} else {
			Matcher m = p.matcher(id);
			if (m.matches()) {
				try {
					Course course = h2CourseDao.selectById(Long.parseLong(id));
					if (course != null) {
						Student student = (Student) request.getSession()
								.getAttribute("student");
						Long studentid = student.getId();
						h2TrainingDao.insert(Long.parseLong(id), studentid);
						Training training = h2TrainingDao.selectById(studentid);
						student.addCourse(training);
						return "/studentscabinet.jsp";
					}
				} catch (Exception e) {
					LOGGER.error("Failed to add a course");
				}
				return "/studentscabinet.jsp";
			} else {
				request.getSession().setAttribute("errorMessage",
						" Id consists of numbers only");
				request.getSession().setAttribute("initialpage",
						"/studentscabinet.jsp");
				return "/errormessage.jsp";
			}
		}
	}
	
}
